package dingding

import (
	"fmt"

	openapi "github.com/alibabacloud-go/darabonba-openapi/client"
	ddcontact "github.com/alibabacloud-go/dingtalk/contact_1_0"
	oauth "github.com/alibabacloud-go/dingtalk/oauth2_1_0"
	util "github.com/alibabacloud-go/tea-utils/service"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
)

type DingDingAuthController struct {
	Ctx iris.Context
}

func (c *DingDingAuthController) BeforeActivation(b mvc.BeforeActivation) {
	b.Handle("GET", "/login", "Login") // /dd/login
}

func (c *DingDingAuthController) getConfig() *openapi.Config {
	appkey := "dingtjzgjyrj8rvjlakk"
	appsecret := "_kUxo2eEQmc7Etla-aALpkrFgBUrLq2IWCWMvRp6tbruylwonqV-TnDif-qEdWuk"
	protocol := "https"
	regionId := "central"
	config := openapi.Config{
		AccessKeyId:     &appkey,
		AccessKeySecret: &appsecret,
		Protocol:        &protocol,
		RegionId:        &regionId,
	}

	return &config
}

func (c *DingDingAuthController) Login() {
	// authCode=c4ea41cbb8ac32c0941338fc8a75b180&state=1
	authCode := c.Ctx.URLParam("authCode")
	// state := c.Ctx.URLParam("state")

	config := c.getConfig()
	// init client
	client, err := oauth.NewClient(config)
	if err != nil {
		c.Ctx.WriteString(err.Error())
		return
	}
	// init request
	request := new(oauth.GetUserTokenRequest)
	request.SetClientId(*config.AccessKeyId)
	request.SetClientSecret(*config.AccessKeySecret)
	request.SetCode(authCode)
	request.SetGrantType("authorization_code")

	// call api
	resp, err := client.GetUserToken(request)
	if err != nil {
		fmt.Print(err)
		c.Ctx.WriteString(err.Error())
		return
	}

	token := resp.Body.AccessToken

	c.GetUserInfoByToken(*token)
}

func (c *DingDingAuthController) GetUserInfoByToken(token string) {
	//  com.aliyun.dingtalkcontact_1_0.Client client = contactClient();
	//         GetUserHeaders getUserHeaders = new GetUserHeaders();
	//         getUserHeaders.xAcsDingtalkAccessToken = accessToken;
	//         //获取用户个人信息，如需获取当前授权人的信息，unionId参数必须传me
	//         String me = JSON.toJSONString(client.getUserWithOptions("me", getUserHeaders, new RuntimeOptions()).getBody());
	//         System.out.println(me);
	//         return me;

	client, _ := ddcontact.NewClient(c.getConfig())

	headers := &ddcontact.GetUserHeaders{
		XAcsDingtalkAccessToken: &token,
	}

	runtimeOpt := &util.RuntimeOptions{}

	//获取用户个人信息，如需获取当前授权人的信息，unionId参数必须传me
	//         String me = JSON.toJSONString(client.getUserWithOptions("me", getUserHeaders, new RuntimeOptions()).getBody());
	//         System.out.println(me);

	me := "me"
	resp, err := client.GetUserWithOptions(&me, headers, runtimeOpt)
	if err != nil {
		c.Ctx.WriteString(err.Error())
		return
	}

	c.Ctx.WriteString(resp.GoString())

}
